﻿using CoreShop.Model;
using Sunny.UI;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management;
using System.Net.Mail;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace CoreShop.Library
{
    public class CommFunc
    {
        [DllImport("winmm.dll")]
        public static extern bool PlaySound(string pszSound, int hmod, int fdwSound);
        public static void sound(int playType)
        {            
            try
            {
                const int SND_FILENAME = 0x00020000;
                const int SND_ASYNC = 0x0001;
                switch (playType)
                {
                    case (int)GlobalEnumVars.OrderPlaySound.Woman:
                        PlaySound(@"Ding.wav", 0, SND_ASYNC | SND_FILENAME);
                        break;
                    case (int)GlobalEnumVars.OrderPlaySound.Man:
                        PlaySound(@"Ding1.wav", 0, SND_ASYNC | SND_FILENAME);
                        break;
                    default: 
                        return;
                }                
                System.Threading.Thread.Sleep(0);
            }
            catch
            {
            }
        }

        public static string CutString(string str, int len)
        {
            if (str == null || str.Length == 0 || len <= 0)
            {
                return string.Empty;
            }

            int l = str.Length;

            #region 计算长度
            int clen = 0;
            while (clen < len && clen < l)
            {
                //每遇到一个中文，则将目标长度减一。
                if ((int)str[clen] > 128) { len--; }
                clen++;
            }
            #endregion

            if (clen < l)
            {
                return str.Substring(0, clen) + "...";
            }
            else
            {
                return str;
            }
        }

        /// <summary>
        /// 获取单据编码
        /// </summary>
        public static long GetCorpNextId(int storeId, long NextId)
        {
            //return NextId;
            if ((storeId.ToString().Length + NextId.ToString().Length) > 17) return NextId;
            string str = storeId.ToString() + NextId.ToString();
            long orderId = ConvertToBigInt(str);
            if (orderId.ToString().Length < 10) orderId = NextId;
            return orderId;
        }

        /// <summary>
        /// Int32 的字符串  转换为 Boolean 
        /// </summary>
        /// <param name="intstr"></param>
        /// <returns></returns>
        public static Boolean Int32StringToBoolean(String intstr)
        {
            if (intstr.Length < 1)
            {
                return false;
            }
            return (intstr[0] == '0') ? false : true;
        }

        public static Decimal ChinaRound(Decimal value, int decimals)
        {
            Double dValues = Convert.ToDouble(value);
            if (value < 0)
            {
                //decimal dRet  = CommFunc.ConvertDBNullToDecimal(Math.Round(dValues + 5 / Math.Pow(10, decimals + 1), decimals, MidpointRounding.AwayFromZero));
                decimal dRet = CommFunc.ConvertToDecimal(Math.Round(dValues, decimals, MidpointRounding.AwayFromZero));
                return dRet;
            }
            else
            {
                return Math.Round(value, decimals, MidpointRounding.AwayFromZero);
            }
        }


        /// <summary>
        /// 单行数据小数点
        /// </summary>
        /// <param name="amount"></param>
        /// <returns></returns>
        public static decimal GetRowAmount(decimal amount, int amountDecimal)
        {
            switch (amountDecimal)
            {
                case (int)GlobalEnumVars.AmountDecimal.RoundPoint0:
                    return ChinaRound(amount, 0);
                case (int)GlobalEnumVars.AmountDecimal.RoundPoint1:
                    return ChinaRound(amount, 1);
                case (int)GlobalEnumVars.AmountDecimal.RoundPoint2:
                    return ChinaRound(amount, 2);
                case (int)GlobalEnumVars.AmountDecimal.FloorPoint0:
                    return Math.Floor(amount);
                case (int)GlobalEnumVars.AmountDecimal.FloorPoint1:
                    return Math.Floor(amount * 10) / 10;
                case (int)GlobalEnumVars.AmountDecimal.FloorPoint2:
                    return Math.Floor(amount * 100) / 100;
            }
            return amount;
        }

        public static string GetDeskNumber(List<corecmsfoodorderingmaster> orders)
        {
            string numbwrStr = "";//拼台号
            if ((orders != null) && (orders.Count > 0))
            {
                int deskNumber = 0;
                foreach (var order in orders)
                {
                    if (CommFunc.ConvertToInt32(order.number) >= deskNumber)
                        deskNumber = CommFunc.ConvertToInt32(order.number) + 1;
                }
                numbwrStr = deskNumber.ToString();
            }
            return numbwrStr;
        }

        /// <summary>
        /// 合计数据小数点
        /// </summary>
        /// <param name="amount"></param>
        /// <returns></returns>
        public static decimal GetSumAmount(decimal amount,int amountDecimal)
        {
            switch (amountDecimal)
            {
                case (int)GlobalEnumVars.AmountDecimal.RoundPoint0:
                    return ChinaRound(amount, 0);
                case (int)GlobalEnumVars.AmountDecimal.RoundPoint1:
                    return ChinaRound(amount, 1);
                case (int)GlobalEnumVars.AmountDecimal.RoundPoint2:
                    return ChinaRound(amount, 2);
                case (int)GlobalEnumVars.AmountDecimal.FloorPoint0:
                    return Math.Floor(amount);
                case (int)GlobalEnumVars.AmountDecimal.FloorPoint1:
                    return Math.Floor(amount * 10) / 10;
                case (int)GlobalEnumVars.AmountDecimal.FloorPoint2:
                    return Math.Floor(amount * 100) / 100;
            }
            return amount;
        }


        /// <summary>
        /// 判斷編號是否合法
        /// </summary>
        /// <param name="str_no">程序編號</param>
        /// <returns></returns>
        public static bool IsNo(string str_no)
        {
            if (string.IsNullOrEmpty(str_no))
            {
                return true;
            }
            string str_all = "\'\"";
            foreach (char chr in str_no.Trim())
            {
                if (str_all.Contains(chr))
                {
                    return false;
                }
            }
            return true;
        }

        public static bool GetDateString(char c, string text, int index, out string dateString)
        {
            dateString = string.Empty;
            if (index == 0)
            {
                dateString = c.ToString() + text.Substring(index + 1, text.Length - index - 1);
            }
            else if (index < text.Length)
            {
                dateString = text.Substring(0, index) + c.ToString() + text.Substring(index + 1, text.Length - index - 1);
            }
            else
                return false;
            Regex re = new System.Text.RegularExpressions.Regex(@"^[1|2][\d+]{3}-[0-1][\d+]-[0-3][\d+]$");
            return re.IsMatch(dateString);
        }

        /// <summary>
        /// 驗証字符串是否為日期
        /// </summary>
        /// <param name="strInput"></param>
        /// <returns></returns>
        public static bool IsDate(string strInput)
        {
            string datestr = strInput;
            string year, month, day;
            string[] c = { "/", "-", "." };
            string cs = "";
            for (int i = 0; i < c.Length; i++)
            {
                if (datestr.IndexOf(c[i]) > 0)
                {
                    cs = c[i];
                    break;
                }

            };

            if (cs != "")
            {
                year = datestr.Substring(0, datestr.IndexOf(cs));
                if (year.Length != 4) { return false; };
                datestr = datestr.Substring(datestr.IndexOf(cs) + 1);

                month = datestr.Substring(0, datestr.IndexOf(cs));
                if ((month.Length != 2) || (CommFunc.ConvertToInt32(month) > 12))
                { return false; };
                datestr = datestr.Substring(datestr.IndexOf(cs) + 1);

                day = datestr;
                if ((day.Length != 2) || (CommFunc.ConvertToInt32(day) > 31)) { return false; };

                return checkDatePart(year, month, day);
            }
            else
            {
                return false;
            }

        }

        /// <summary>
        /// 检查年月日是否合法
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="part"></param>
        /// <returns></returns>      
        public static DateTime ConvertTimeToDateTime(string time,int addDays)
        {
            string sDateTime = DateTime.Now.AddDays(addDays).ToString("yyyy-MM-dd") +" "+ time;
            return ConvertToDateTime(sDateTime);
        }


        /// <summary>
        /// 检查年月日是否合法
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="part"></param>
        /// <returns></returns>      
        private static bool checkDatePart(string year, string month, string day)
        {
            int iyear = CommFunc.ConvertToInt32(year);
            int imonth = CommFunc.ConvertToInt32(month);
            int iday = CommFunc.ConvertToInt32(day);
            if (iyear > 2099 || iyear < 1900) { return false; }
            if (imonth > 12 || imonth < 1) { return false; }
            if (iday > DateTime.DaysInMonth(iyear, imonth) || iday < 1) { return false; };
            return true;
        }

        private static bool GetTimeString(char c, string text, int index, out string dateString)
        {
            dateString = string.Empty;
            if (index == 0)
            {
                dateString = c.ToString() + text.Substring(index + 1, text.Length - index - 1);
            }
            else if (index < text.Length)
            {
                dateString = text.Substring(0, index) + c.ToString() + text.Substring(index + 1, text.Length - index - 1);
            }
            else
                return false;
            Regex re = new System.Text.RegularExpressions.Regex(@"^[0-2][\d+]:[0-5][\d+]$");
            return re.IsMatch(dateString);
        }

        /// <summary>
        /// 驗証字符串是否為時間
        /// </summary>
        /// <param name="strInput"></param>
        /// <returns></returns>
        public static bool IsTime(string strInput)
        {
            if (string.IsNullOrEmpty(strInput))
                return false;
            string[] str = strInput.Split(':');
            if (str.Length != 2)
                return false;
            int h = 0, m = 0;
            if (int.TryParse(str[0], out h) == false)
                return false;

            if (int.TryParse(str[1], out m) == false)
                return false;
            if (m >= 0 && h < 60 && h >= 0 && h < 24)
                return true;
            return false;

        }

        /// <summary>
        /// 判斷是否為數字
        /// </summary>
        public static bool IsNum(string str)
        {
            if (str.Trim().Equals(""))
                return false;

            for (int i = 0; i < str.Length; i++)
            {
                if (!Char.IsNumber(str, i))
                    return false;
            }
            return true;

        }


        /// <summary>
        /// 去掉小数点后面的零
        /// </summary>
        /// <param name="str"></param>
        /// <param name="len"></param>
        /// <param name="rpl"></param>
        /// <returns></returns>
        public static string FormatDecimal(decimal value)
        {
            try
            {
                string strNum = value.ToString();
                //第二步使用TrimEnd()
                if (strNum.Contains("."))
                {//字符串为浮点数
                    strNum = strNum.TrimEnd('0').TrimEnd('.');//0.5
                }
                return strNum;
            }
            catch (ArgumentException ex)
            {
                return value.ToString();
            }
        }


        public static string Fill_strL(string str, int len, string rpl)//用字符串rpl填充字付串str,數量len
        {
            string str1;
            int v1;
            v1 = str.Trim().Length;

            str1 = "";
            for (int i = v1 + 1; i <= len; i++)
            {
                str1 = str1.Trim() + rpl.Trim();
            }
            return (str1.Trim() + str.Trim());
        }
        public static string GetFirstDay()//獲取當月第一天的日期
        {
            string y, m;
            y = DateTime.Now.Year.ToString();
            m = DateTime.Now.Month.ToString();
            m = Fill_strL(m, 2, "0");
            return (y + "-" + m + "-" + "01");

        }
        public static bool isDateTime(string str)
        {
            bool val;
            try
            {
                Convert.ToDateTime(str);
                val = true;
            }
            catch
            {
                val = false;
            }
            return (val);
        }
        public static bool isDecimal(string str)
        {
            bool val;
            try
            {
                CommFunc.ConvertToDecimal(str);
                val = true;
            }
            catch
            {
                val = false;
            }
            return (val);

        }
        /// <summary>
        /// 轉換null string to space
        /// </summary>
        /// <param name="str1"></param>
        /// <returns></returns>
        public static string ConvertNullString(string str1)
        {
            if (str1 == null)
                return "";
            return str1.Trim();
        }
        /// <summary>
        /// 轉換DBNull to string
        /// </summary>
        /// <param name="obj1"></param>
        /// <returns></returns>
        public static string ConvertToString(Object obj1)
        {
            if (Convert.IsDBNull(obj1) || obj1 == null)
            {
                return "";
            }
            else
            {
                return obj1.ToString().Trim();
            }
        }

        /// <summary>
        /// 轉換DBNull to string 加上引号
        /// </summary>
        /// <param name="obj1"></param>
        /// <returns></returns>
        public static string ConvertStrValue(Object obj1)
        {
            try
            {
                if (Convert.IsDBNull(obj1) || obj1 == null)
                {
                    return "";
                }
                else
                {
                    string str1 = Convert.ToString(obj1).Trim().Replace("\r\n", "").Replace("'", "");
                    return str1.ToString().Trim();
                }
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// 轉換DBNull to Short
        /// </summary>
        /// <param name="obj1"></param>
        /// <returns></returns>
        public static short ConvertToInt16(Object obj1)
        {
            short rtn1 = 0;
            try
            {
                if (Convert.IsDBNull(obj1) || obj1 == null)
                {
                    rtn1 = 0;
                }
                else
                {
                    if (obj1.ToString().Trim().Length > 0)
                    {
                        short.TryParse(obj1.ToString(), out rtn1);
                    }
                }
                return rtn1;
            }
            catch
            {
                return rtn1;
            }
        }

        /// <summary>
        /// 轉換DBNull to Int
        /// </summary>
        /// <param name="obj1"></param>
        /// <returns></returns>
        public static int ConvertToInt32(Object obj1)
        {
            int rtn1 = 0;
            try
            {
                if (Convert.IsDBNull(obj1) || obj1 == null)
                {
                    rtn1 = 0;
                }
                else
                {
                    if (obj1.ToString().Trim().Length > 0)
                    {
                        int.TryParse(obj1.ToString(), out rtn1);
                    }
                }
                return rtn1;
            }
            catch
            {
                return rtn1;
            }
        }

        /// <summary>
        /// 轉換DBNull to Int
        /// </summary>
        /// <param name="obj1"></param>
        /// <returns></returns>
        public static Int16 ConvertBoolToInt16(Object obj1)
        {
            Int16 rtn1 = 0;
            try
            {
                if (Convert.IsDBNull(obj1) || obj1 == null)
                {
                    rtn1 = 0;
                }
                else
                {
                    try
                    {
                        bool mret = Convert.ToBoolean(obj1);
                        if (mret == true)
                        {
                            rtn1 = 1;
                        }
                        else
                        {
                            rtn1 = 0;
                        }
                    }
                    catch
                    {
                        rtn1 = 0;
                    }
                }
                return rtn1;
            }
            catch
            {
                return rtn1;
            }
        }

        public static Int64 ConvertToBigInt(object obj)
        {
            try
            {
                if (obj == null)
                {
                    return 0;
                }
                if (obj == DBNull.Value)
                {
                    return 0;
                }
                return Convert.ToInt64(obj);
            }
            catch (Exception E)
            {
                return 0;
            }
        }

        public static bool ConvertIntToBool(object obj)
        {
            try
            {
                if (obj == null)
                {
                    return false;
                }
                if (obj == DBNull.Value)
                {
                    return false;
                }
                return bool.Parse(ConvertToInt32(obj) == 1 ? "true" : "false");
            }
            catch (Exception E)
            {
                return false;
            }
        }

        /// <summary>
        /// 轉換DBNull to Booten
        /// </summary>
        /// <param name="obj1"></param>
        /// <returns></returns>
        public static Boolean ConvertToBooten(Object obj1)
        {
            Boolean mret = false;
            try
            {
                if (Convert.IsDBNull(obj1) || obj1 == null)
                {
                    mret = false;
                }
                else
                {
                    if (obj1.ToString().Trim().Length > 0)
                    {
                        mret = Convert.ToBoolean(obj1);
                    }
                }
            }
            catch
            {
            }
            return mret;
        }

        /// <summary>
        /// 轉換DBNull to Booten
        /// </summary>
        /// <param name="obj1"></param>
        /// <returns></returns>
        public static int ConvertToBtInt(Object obj1)
        {
            int mret = 0;
            try
            {
                if (Convert.IsDBNull(obj1) || obj1 == null)
                {
                    mret = 0;
                }
                else
                {
                    if (obj1.ToString().Trim().Length > 0)
                    {
                        Int32.TryParse(obj1.ToString(), out mret);
                    }
                }
            }
            catch
            {
            }
            return mret;
        }

        /// <summary>
        /// 轉換DBNull to Int64
        /// </summary>
        /// <param name="obj1"></param>
        /// <returns></returns>
        public static Int64 ConvertToInt64(Object obj1)
        {
            Int64 mret = 0;
            try
            {
                if (Convert.IsDBNull(obj1) || obj1 == null)
                {
                    mret = 0;
                }
                else
                {
                    if (obj1.ToString().Trim().Length > 0)
                    {
                        Int64.TryParse(obj1.ToString(), out mret);
                    }
                }
            }
            catch
            {
            }
            return mret;
        }

        /// <summary>
        /// 轉換DBNull to Booten
        /// </summary>
        /// <param name="obj1"></param>
        /// <returns></returns>
        public static int ConvertToBitValue(Object obj1)
        {
            int mret = 0;
            try
            {
                if (Convert.IsDBNull(obj1) || obj1 == null)
                {
                    mret = 0;
                }
                else
                {
                    bool mbool = Convert.ToBoolean(obj1);

                    if (mbool)
                    {
                        mret = 1;
                    }
                    else
                    {
                        mret = 0;
                    }
                }
            }
            catch
            {
            }
            return mret;
        }

        /// <summary>
        /// 轉換DBNull to Decimal
        /// </summary>
        /// <param name="obj1"></param>
        /// <returns></returns>
        public static Decimal ConvertToDecimal(Object obj1)
        {
            Decimal rtn1 = 0;
            if (Convert.IsDBNull(obj1) || obj1 == null)
            {
                rtn1 = 0;
            }
            else
            {
                if (obj1.ToString().Trim().Length > 0)
                {
                    Decimal.TryParse(obj1.ToString(), out rtn1);
                }
            }
            return rtn1;
        }

        /// <summary>
        /// 轉換DBNull to Decimal
        /// </summary>
        /// <param name="obj1"></param>
        /// <returns></returns>
        public static Decimal ConvertToDecimal2(Object obj1)
        {
            Decimal rtn1 = 0;
            if (Convert.IsDBNull(obj1) || obj1 == null)
            {
                rtn1 = 0;
            }
            else
            {
                if (obj1.ToString().Trim().Length > 0)
                {
                    Decimal.TryParse(obj1.ToString(), out rtn1);
                    if ((rtn1 > 99999999) || (rtn1 < -99999999)) rtn1 = 0;
                }
            }
            return rtn1;
        }

        /// <summary>
        /// 轉換DBNull to Double
        /// </summary>
        /// <param name="obj1"></param>
        /// <returns></returns>
        public static Double ConvertToDouble(Object obj1)
        {
            Double rtn1 = 0;
            if (Convert.IsDBNull(obj1) || obj1 == null)
            {
                rtn1 = 0;
            }
            else
            {
                if (obj1.ToString().Trim().Length > 0)
                {
                    Double.TryParse(obj1.ToString(), out rtn1);
                }
            }
            return rtn1;
        }
        /// <summary>
        /// 轉換DBNull to float
        /// </summary>
        /// <param name="obj1"></param>
        /// <returns></returns>
        public static float ConvertToFloat(Object obj1)
        {
            float rtn1 = 0;
            if (Convert.IsDBNull(obj1) || obj1 == null)
            {
                rtn1 = 0;
            }
            else
            {
                if (obj1.ToString().Trim().Length > 0)
                {
                    float.TryParse(obj1.ToString(), out rtn1);
                }
            }
            return rtn1;
        }

        /// <summary>  
        /// 获取时间戳  
        /// </summary>  
        /// <returns></returns>  
        public static Int64 GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(2000, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds);
        }

        public static Int64 GetTimeStamp(DateTime inputDateTime)
        {
            DateTime utcDateTime = inputDateTime.ToUniversalTime();
            // 定义基准时间
            DateTime baseDateTime = new DateTime(2000, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            // 计算时间间隔
            TimeSpan ts = utcDateTime - baseDateTime;
            // 返回时间间隔的总秒数作为时间戳
            return Convert.ToInt64(ts.TotalSeconds);
        }

        public static DateTime ConvertTimestampToDateTime(long timestamp)
        {
            // 定义基准时间
            DateTime baseDateTime = new DateTime(2000, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            // 在基准时间上加上时间戳所代表的秒数
            DateTime utcDateTime = baseDateTime.AddSeconds(timestamp);
            // 转换为本地时间
            return utcDateTime.ToLocalTime();
        }


        /// <summary>
        /// 轉換DBNull to Datetime
        /// </summary>
        /// <param name="obj1"></param>
        /// <returns></returns>
        public static DateTime ConvertToDateTime(Object obj1)
        {
            DateTime rtn1 = new DateTime();
            if (Convert.IsDBNull(obj1) || obj1 == null || ConvertToString(obj1) == "")
            {
                rtn1 = new DateTime(2000, 1, 1);
            }
            else
            {
                if (obj1.ToString().Trim().Length > 0)
                {
                    DateTime.TryParse(obj1.ToString(), out rtn1);
                }
            }
            return rtn1;
        }
        /// <summary>
        /// 獲取日期時間格式
        /// </summary>
        /// <returns></returns>

        /// <summary>
        /// C#小数转换分数,取分母
        /// </summary>
        /// <returns></returns>
        public static int ConvertToFractionParent(float fNum)
        {
            float fTemp;
            fTemp = fNum;
            int iFactor = 1;
            int iNum;

            while (CommFunc.ConvertToInt32(fNum) != fNum)
            {
                fNum *= 10;
                iFactor *= 10;
            }

            iNum = CommFunc.ConvertToInt32(fNum);

            int iDiv = MaxCommonDivisor(iNum, iFactor);
            int strDenominator = iFactor / iDiv;
            return (strDenominator);
        }
        /// <summary>
        /// C#小数转换分数,取分子
        /// </summary>
        /// <returns></returns>
        public static int ConvertToFractionSon(float fNum)
        {
            float fTemp;
            fTemp = fNum;
            int iFactor = 1;
            int iNum;

            while (CommFunc.ConvertToInt32(fNum) != fNum)
            {
                fNum *= 10;
                iFactor *= 10;
            }

            iNum = CommFunc.ConvertToInt32(fNum);

            int iDiv = MaxCommonDivisor(iNum, iFactor);
            int strNumerator = iNum / iDiv;
            return (strNumerator);
        }

        /// <summary>
        /// C#小数转换分数（转）
        /// </summary>
        /// <returns></returns>
        public static string ConvertToFraction(float fNum)
        {
            float fTemp;
            fTemp = fNum;
            int iFactor = 1;
            int iNum;

            while (CommFunc.ConvertToInt32(fNum) != fNum)
            {
                fNum *= 10;
                iFactor *= 10;
            }

            iNum = CommFunc.ConvertToInt32(fNum);

            int iDiv = MaxCommonDivisor(iNum, iFactor);
            string strNumerator = iNum / iDiv + "";
            string strDenominator = iFactor / iDiv + "";
            return (strNumerator + "/" + strDenominator);
        }

        private static int MaxCommonDivisor(int iNum1, int iNum2)
        {
            int a = iNum1;
            int b = iNum2;
            int temp;

            while (b != 0)/*利用辗除法，直到b为0为止*/
            {
                temp = a % b;
                a = b;
                b = temp;
            }

            return a;
        }

        /// <summary>
        /// 字符串加1方法
        /// </summary>
        /// <param name="NumberStr"></param>
        /// <returns></returns>
        public static string IncString(string NumberStr)
        {
            if (NumberStr == "") return "";
            char[] NumberChar = NumberStr.ToCharArray();
            bool JW = true; //进位
            int CharIndex = NumberStr.Length - 1;
            string ResultStr = "";

            while (CharIndex >= 0)
            {
                if (JW == true)
                {
                    JW = false;
                    if (NumberStr[CharIndex] == '9' || NumberStr[CharIndex] == 'Z' || NumberStr[CharIndex] == 'z')
                    {
                        ResultStr = "0" + ResultStr;
                        JW = true;
                    }
                    else
                    {
                        int ASCIIValue = (int)NumberStr[CharIndex] + 1;
                        char ASCII = (char)ASCIIValue;
                        ResultStr = new string(ASCII, 1) + ResultStr;
                    }
                }
                else
                {
                    ResultStr = new string(NumberStr[CharIndex], 1) + ResultStr;
                }
                CharIndex--;
            }
            return ResultStr;
        }

        /// <summary>
        /// 發郵件函數
        /// </summary>
        /// <param name="subj1">主題</param>
        /// <param name="mailcont1">郵件正文</param>
        /// <param name="fromEmail">发件人Email(為空就是配置文件指定的發件人)</param>
        /// <param name="listReceipts">收件人列表</param>
        /// <param name="listCCs">副本列表</param>
        /// <param name="listAttachments">附件列表,如: c:\\temp\test.xls </param>
        /// <summary>
        /// 發郵件函數
        /// </summary>
        /// <param name="subj1">主題</param>
        /// <param name="mailcont1">郵件正文</param>
        /// <param name="fromEmail">发件人Email(為空就是配置文件指定的發件人)</param>
        /// <param name="listReceipts">收件人列表</param>
        /// <param name="listCCs">副本列表</param>
        /// <param name="listAttachments">附件列表,如: c:\\temp\test.xls </param>
        /// <param name="listBCC">密件副本列表</param>
        /// <param name="msg">返回錯誤信息</param>
        /// <summary>
        /// 讀取配置文件的信息
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>

        public static string get_DataTable_Join_String(Dictionary<string, string> columns_Dict, List<Dictionary<string, string>> List_Join_Dict, Dictionary<string, string> Where_Dict, string Order_str)
        {
            string strWhere = "";
            string str_from = "";
            string str_table_name_0 = "";
            string str_table_name_1 = "";
            string str_join = "";
            string columns = "";
            string str_Join_Column = "";
            string strSql = "";

            //Join
            int i = 0;
            foreach (Dictionary<string, string> Dict in List_Join_Dict)
            {
                str_table_name_0 = "";
                str_table_name_1 = "";
                str_Join_Column = "";
                i = 0;
                foreach (KeyValuePair<string, string> item in Dict)
                {
                    if (str_from == "")
                    {
                        str_from = item.Key;
                        str_table_name_0 = item.Key;
                        str_join = item.Value.Trim();
                        str_table_name_1 = str_join.Substring(str_join.LastIndexOf(" "));
                        strSql = string.Format(@"
from {0}
{1} ", str_from, str_join);
                    }
                    else if (str_table_name_0 == "")
                    {
                        str_table_name_0 = item.Key;
                        str_join = item.Value.Trim();
                        str_table_name_1 = str_join.Substring(str_join.LastIndexOf(" "));
                        strSql = strSql + string.Format(@"
{0} ", str_join);
                    }
                    else
                    {
                        if (i == 5)
                        {
                            i = 0;
                            str_Join_Column += "\r\n";
                        }
                        str_Join_Column += ((str_Join_Column == "") ? "" : " And ") + str_table_name_0 + "." + item.Key + "=" + str_table_name_1 + "." + item.Value;
                        i++;
                    }
                }
                strSql = strSql + "on\r\n" + str_Join_Column;
            }
            //列
            i = 0;
            foreach (KeyValuePair<string, string> item in columns_Dict)
            {
                if (i == 5)
                {
                    i = 0;
                    columns += "\r\n";
                }
                if (item.Value == "")
                {
                    columns += ((columns == "") ? "" : ", ") + item.Key;
                }
                else
                {
                    columns += ((columns == "") ? "" : ", ") + item.Value + " as " + item.Key;
                }
                i++;
            }
            i = 0;
            foreach (KeyValuePair<string, string> item in Where_Dict)
            {
                if (i == 5)
                {
                    i = 0;
                    columns += "\r\n";
                }
                if (item.Value == "")
                {
                    strWhere += ((strWhere == "") ? "" : " And ") + item.Key;
                }
                else
                {
                    strWhere += ((strWhere == "") ? "" : " And ") + item.Key + "=" + item.Value;
                }
                i++;
            }
            strSql = "Select " + columns + strSql + " \r\nWhere " + strWhere + Order_str;
            //DataSet ds = DbHelperSQL.Query(strSql);
            return strSql;
        }


        /// <summary>
        /// 匯出Excel
        /// </summary>
        /// <param name="dict"></param>

        /// <summary>
        /// 控制輸入小數
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void textBox_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (!(e.KeyChar >= '0' && e.KeyChar <= '9'))
            {
                e.Handled = true;
            }
            if (e.KeyChar == '\b' || (CommFunc.ConvertToInt32(e.KeyChar) == 46))
            {
                e.Handled = false;
            }
            if (CommFunc.ConvertToInt32(e.KeyChar) == 46 && ((System.Windows.Forms.TextBox)sender).Text.IndexOf('.') > -1)
            {
                e.Handled = true;
            }
        }

        /// <summary>
        /// 控制輸入小數
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void decimalBox_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (!(e.KeyChar >= '0' && e.KeyChar <= '9'))
            {
                e.Handled = true;
            }
            if (e.KeyChar == '\b' || (CommFunc.ConvertToInt32(e.KeyChar) == 46))
            {
                e.Handled = false;
            }
            if (CommFunc.ConvertToInt32(e.KeyChar) == 46 && ((System.Windows.Forms.TextBox)sender).Text.IndexOf('.') > -1)
            {
                e.Handled = true;
            }
        }

        /// <summary>
        /// 控制輸入整數
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void intBox_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (!(e.KeyChar >= '0' && e.KeyChar <= '9'))
            {
                e.Handled = true;
            }
            if (e.KeyChar == '\b')
            {
                e.Handled = false;
            }
        }

        /// <summary>
        /// 控制輸入小數
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void decimalCell_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (!(e.KeyChar >= '0' && e.KeyChar <= '9'))
            {
                e.Handled = true;
            }
            if (e.KeyChar == '\b' || (CommFunc.ConvertToInt32(e.KeyChar) == 46))
            {
                e.Handled = false;
            }
            if (CommFunc.ConvertToInt32(e.KeyChar) == 46 && ((System.Windows.Forms.DataGridViewTextBoxEditingControl)sender).Text.ToString().IndexOf('.') > -1)
            {
                e.Handled = true;
            }
        }
        /// <summary>
        /// 控制輸入整數
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void intCell_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (!(e.KeyChar >= '0' && e.KeyChar <= '9'))
            {
                e.Handled = true;
            }
            if (e.KeyChar == '\b')
            {
                e.Handled = false;
            }
        }
        ///// <summary>
        ///// 控制小數
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //public static void TextBoxDec_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        //{
        //    if (e.KeyChar != 8 && !Char.IsDigit(e.KeyChar) && e.KeyChar != '.')
        //    {
        //        e.Handled = true;
        //    }
        //    else
        //    {
        //        if ((sender as System.Windows.Forms.TextBoxBase) == null)
        //        {
        //            e.Handled = true;
        //        }
        //        else
        //        {
        //            if (e.KeyChar == '.')
        //            {
        //                string xyStr = (sender as System.Windows.Forms.TextBoxBase).Text.ToString().Trim();
        //                if (xyStr.Contains("."))
        //                {
        //                    e.Handled = true;
        //                }
        //            }
        //        }
        //    }
        //}

        /// <summary>
        /// 关联两个DataTable对象
        /// </summary>
        /// <param name="First"></param>
        /// <param name="Second"></param>
        /// <param name="FJC"></param>
        /// <param name="SJC"></param>
        /// <returns></returns>
        public static DataTable JoinDataTable(DataTable First, DataTable Second, DataColumn[] FJC, DataColumn[] SJC)
        {
            //创建一个新的DataTable
            DataTable table = new DataTable("Join");
            using (DataSet ds = new DataSet())
            {
                //把DataTable Copy到DataSet中
                ds.Tables.AddRange(new DataTable[] { First.Copy(), Second.Copy() });

                DataColumn[] parentcolumns = new DataColumn[FJC.Length];

                for (int i = 0; i < parentcolumns.Length; i++)
                {
                    parentcolumns[i] = ds.Tables[0].Columns[FJC[i].ColumnName];
                }

                DataColumn[] childcolumns = new DataColumn[SJC.Length];

                for (int i = 0; i < childcolumns.Length; i++)
                {
                    childcolumns[i] = ds.Tables[1].Columns[SJC[i].ColumnName];
                }

                //创建关联
                DataRelation r = new DataRelation(string.Empty, parentcolumns, childcolumns, false);
                ds.Relations.Add(r);

                //为关联表创建列
                for (int i = 0; i < First.Columns.Count; i++)
                {
                    table.Columns.Add(First.Columns[i].ColumnName, First.Columns[i].DataType);
                }

                for (int i = 0; i < Second.Columns.Count; i++)
                {
                    //看看有没有重复的列，如果有在第二个DataTable的Column的列明后加_Second
                    if (!table.Columns.Contains(Second.Columns[i].ColumnName))
                        table.Columns.Add(Second.Columns[i].ColumnName, Second.Columns[i].DataType);
                    else
                        table.Columns.Add(Second.Columns[i].ColumnName + "_Second", Second.Columns[i].DataType);
                }

                table.BeginLoadData();

                foreach (DataRow firstrow in ds.Tables[0].Rows)
                {
                    //得到行的数据
                    DataRow[] childrows = firstrow.GetChildRows(r);

                    if (childrows != null && childrows.Length > 0)
                    {
                        object[] parentarray = firstrow.ItemArray;

                        foreach (DataRow secondrow in childrows)
                        {
                            object[] secondarray = secondrow.ItemArray;
                            object[] joinarray = new object[parentarray.Length + secondarray.Length];
                            Array.Copy(parentarray, 0, joinarray, 0, parentarray.Length);
                            Array.Copy(secondarray, 0, joinarray, parentarray.Length, secondarray.Length);
                            table.LoadDataRow(joinarray, true);
                        }
                    }
                }
                table.EndLoadData();
            }
            return table;
        }

        /// <summary>
        /// 由傳入的sDataTable得到一個新的DataTable
        /// </summary>
        /// <param name="sDataTable"></param>
        /// <param name="columns"></param>
        /// <returns></returns>
        public static DataTable CopyColumnsTable(DataTable sDataTable, DataTable fDataTable)
        {
            DataTable table = sDataTable.Copy();
        Columns_Remove:
            foreach (DataColumn item in table.Columns)
            {
                if (!fDataTable.Columns.Contains(item.ColumnName))
                {
                    table.Columns.Remove(item);
                    goto Columns_Remove;
                }
            }
            return table;
        }

        /// <summary>
        /// 由傳入的sDataTable得到一個新的DataTable
        /// </summary>
        /// <param name="sDataTable"></param>
        /// <param name="columns"></param>
        /// <returns></returns>
        public static DataTable CopyColumnsTable(DataTable sDataTable, string columns)
        {
            DataTable table = sDataTable.Copy();
        Columns_Remove:
            foreach (DataColumn item in table.Columns)
            {
                if (columns.IndexOf(item.ColumnName + ",") == -1 && columns.IndexOf("," + item.ColumnName) == -1)
                {
                    table.Columns.Remove(item);
                    goto Columns_Remove;
                }
            }
            return table;
        }

        ///// <summary>
        ///// DataTable 查詢
        ///// </summary>
        //public static DataTable DataTableSelect(DataTable dt_in, string p_Select)
        //{
        //    DataTable dt_out = dt_in.Clone();
        //    DataRow[] rows = dt_in.Select(p_Select);
        //    foreach (DataRow item in rows)
        //    {
        //        dt_out.ImportRow(item);
        //    }
        //    return dt_out;
        //}

        ///// <summary>
        ///// DataTable 查詢
        ///// </summary>
        //public static DataTable DataTableSelect(DataTable dt_in, DataRow item)
        //{
        //    DataTable dt_out = dt_in.Clone();
        //    dt_out.ImportRow(item);
        //    return dt_out;
        //}


        ///// <summary>
        ///// DataTable 查詢
        ///// </summary>
        //public static void getDataTableString(DataTable dt_in)
        //{
        //    string out_s = "";
        //    string row_s = "";
        //    foreach (DataColumn item in dt_in.Columns)
        //    {
        //        row_s += ((row_s == "") ? "" : Chr(9)) + item.ColumnName;
        //    }
        //    out_s = row_s + "\r\n";
        //    foreach (DataRow item in dt_in.Rows)
        //    {
        //        row_s = "";
        //        foreach (DataColumn item1 in dt_in.Columns)
        //        {
        //            row_s += ((row_s == "") ? "" : Chr(9)) + item[item1.ColumnName].ToString();
        //        }
        //        out_s += row_s + "\r\n";
        //    }
        //    System.IO.FileStream fs = new System.IO.FileStream(@"C:\testDataTable.txt", System.IO.FileMode.Create);
        //    System.IO.StreamWriter sw = new System.IO.StreamWriter(fs);
        //    //开始写入
        //    sw.WriteLine("");
        //    //清空缓冲区
        //    sw.Flush();
        //    //关闭流
        //    sw.Close();
        //    fs.Close();

        //    sw = System.IO.File.AppendText(@"C:\testDataTable.txt");
        //    sw.Write(out_s + "\r\n");
        //    sw.Flush();
        //    sw.Close();
        //}

        ///// <summary>
        ///// ASCII码转字符：
        ///// </summary>
        ///// <param name="asciiCode"></param>
        ///// <returns></returns>
        //public static string Chr(int asciiCode)
        //{
        //    if (asciiCode >= 0 && asciiCode <= 255)
        //    {
        //        System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
        //        byte[] byteArray = new byte[] { (byte)asciiCode };
        //        string strCharacter = asciiEncoding.GetString(byteArray);
        //        return (strCharacter);
        //    }
        //    else
        //    {
        //        throw new Exception("ASCII Code is not valid.");
        //    }
        //}

        /// <summary>
        /// Create by : Liucj Create Time : 2014-10-17
        /// roundUp 或 roundDown數據
        /// </summary>
        /// <param name="target">目標數值</param>
        /// <param name="deci_ind"> 0: 整數,1: 1位小數,2: 2位小數,3: 0.5或整數 **(其他不用Round)</param>
        /// <param name="roundUp">roundUp 后的數值</param>
        /// <param name="roundDown">roundDown 后的數值</param>
        public static void Round(decimal target, int deci_ind, out decimal roundUp, out decimal roundDown)
        {
            roundUp = target;
            roundDown = target;
            decimal qtyTmp0 = 0, qtyTmp1 = 0;
            switch (deci_ind)
            {
                case 0:
                    roundUp = Math.Ceiling(target);
                    roundDown = Math.Floor(target);
                    break;
                case 1:
                    qtyTmp0 = target - Math.Floor(target);
                    qtyTmp1 = CommFunc.ConvertToDecimal(qtyTmp0.ToString("f8").Substring(0, 3));
                    if (qtyTmp0 != qtyTmp1)
                    {
                        roundUp = Math.Floor(target) + qtyTmp1 + CommFunc.ConvertToDecimal("0.1");
                        roundDown = Math.Floor(target) + qtyTmp1;
                    }
                    break;
                case 2:
                    qtyTmp0 = target - Math.Floor(target);
                    qtyTmp1 = CommFunc.ConvertToDecimal(qtyTmp0.ToString("f8").Substring(0, 4));
                    if (qtyTmp0 != qtyTmp1)
                    {
                        roundUp = Math.Floor(target) + qtyTmp1 + CommFunc.ConvertToDecimal("0.01");
                        roundDown = Math.Floor(target) + qtyTmp1;
                    }
                    break;
                case 3:
                    qtyTmp0 = target - Math.Floor(target);
                    qtyTmp1 = qtyTmp0;
                    if (qtyTmp0 != 0 && qtyTmp0 != CommFunc.ConvertToDecimal("0.5"))
                    {
                        if (qtyTmp1 >= CommFunc.ConvertToDecimal("0.5"))
                        {
                            roundUp = Math.Floor(target) + 1;
                            roundDown = Math.Floor(target) + CommFunc.ConvertToDecimal("0.5");
                        }
                        else
                        {
                            roundUp = Math.Floor(target) + CommFunc.ConvertToDecimal("0.5");
                            roundDown = Math.Floor(target);
                        }
                    }
                    break;
                default:
                    break;
            }
        }
        /// <summary>
        /// 保存一个二进制文件到磁盘指定路径
        /// </summary>
        /// <param name="path">磁盘路径</param>
        /// <param name="bytes">二进制数据</param>
        /// <returns></returns>
        public static bool SaveExcelFile(string path, byte[] bytes)
        {
            try
            {
                if (System.IO.File.Exists(path))
                {
                    System.IO.File.Delete(path);
                }
                System.IO.FileStream file = new System.IO.FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                file.Write(bytes, 0, bytes.Length);
                file.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }


        public static DataColumn[] Get_Columns(DataTable dt, string col_names)
        {
            List<DataColumn> lc = new List<DataColumn>();
            string[] ss = col_names.Split(',');
            foreach (string item in ss)
            {
                lc.Add(dt.Columns[item]);
            }
            return lc.ToArray();
        }

        /// <summary>
        /// DataGridView的ColumnType
        /// </summary>
        public enum DataGridViewColumnEnum
        {
            DataGridViewTextBoxColumn = 0,
            DataGridViewCheckBoxColumn = 1
        }

        public static DataGridViewColumn DataColumnToGridViewColumn(DataColumn item, Dictionary<string, DataGridViewColumnEnum> ct, Dictionary<string, string> cn, Dictionary<string, int> cw, Dictionary<string, bool> cr)
        {
            DataGridViewColumn gc; //= new DataGridViewColumn();
            switch (ct[item.ColumnName])
            {
                case DataGridViewColumnEnum.DataGridViewTextBoxColumn:
                    gc = new DataGridViewTextBoxColumn();
                    break;
                case DataGridViewColumnEnum.DataGridViewCheckBoxColumn:
                    gc = new DataGridViewCheckBoxColumn();
                    break;
                default:
                    gc = new DataGridViewTextBoxColumn();
                    break;
            }
            gc.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            gc.HeaderText = cn[item.ColumnName];
            gc.Name = item.ColumnName;
            gc.DataPropertyName = item.ColumnName;
            gc.Width = cw[item.ColumnName];
            gc.ReadOnly = cr[item.ColumnName];
            return gc;
        }

        public static void SetDataGridViewColumn(string name, int weight, DataGridViewColumnEnum dataGridViewColumnEnum, string hideText, bool isReadOnly, Dictionary<string, int> cw, Dictionary<string, DataGridViewColumnEnum> ct, Dictionary<string, string> cn, Dictionary<string, bool> cr)
        {
            cw.Add(name, weight);
            ct.Add(name, dataGridViewColumnEnum);
            cn.Add(name, hideText);
            cr.Add(name, isReadOnly);
        }
        public static void write_datetime()
        {
            string path = "C:\\DateTime.txt";
            if (!File.Exists(path))
            {
                FileInfo myfile = new FileInfo(path);
                FileStream fs = myfile.Create();
                fs.Close();
            }
            StreamWriter sw = File.AppendText(path);
            sw.WriteLine(DateTime.Now.ToString() + " " + DateTime.Now.Millisecond.ToString());
            sw.Flush();
            sw.Close();
        }
        public static void write_datetime(string writeStr)
        {
            string path = "C:\\DateTime.txt";
            if (!File.Exists(path))
            {
                FileInfo myfile = new FileInfo(path);
                FileStream fs = myfile.Create();
                fs.Close();
            }
            StreamWriter sw = File.AppendText(path);
            sw.WriteLine(DateTime.Now.ToString() + " " + DateTime.Now.Millisecond.ToString() + "  " + writeStr);
            sw.Flush();
            sw.Close();
        }
        /// <summary>
        /// 郵件設置里的地址
        /// </summary>
        /// <param name="prog_id"></param>
        /// <returns></returns>
        public static string ConvertToDateString(DateTime? dateTime, string style)
        {
            if (dateTime != null)
            {
                return dateTime.Value.ToString(style);
            }
            return "";
        }

        /// <summary>
        /// 郵件設置里的地址
        /// </summary>
        /// <param name="prog_id"></param>
        /// <returns></returns>
        public static string ConvertDateTimeToString(DateTime dateTime)
        {
            return dateTime.ToString("yyyy-MM-dd HH:mm:ss");
        }

        /// <summary>  
        /// 执行注册表导入  
        /// </summary>  
        /// <param name="regPath">注册表文件路径</param>  
        public static void SetExecuteReg(string regPath)
        {
            if (File.Exists(regPath))
            {
                regPath = @"""" + regPath + @"""";
                Process.Start("regedit", string.Format(" /s {0}", regPath));
            }
        }

        public static bool StartProcess(string filename, string[] args)
        {
            try
            {
                string s = "";
                foreach (string arg in args)
                {
                    s = s + arg + " ";
                }
                s = s.Trim();
                Process myprocess = new Process();
                ProcessStartInfo startInfo = new ProcessStartInfo(filename, s);
                myprocess.StartInfo = startInfo;
                //通过以下参数可以控制exe的启动方式，具体参照 myprocess.StartInfo.下面的参数，如以无界面方式启动exe等
                myprocess.StartInfo.UseShellExecute = false;
                myprocess.Start();
                //myprocess.WaitForExit();
                //myprocess.Close();
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("启动应用程序时出错！原因：" + ex.Message);
            }
            return false;
        }

      

        public static string GetValidJson(string json)
        {
            string myjson = "";
            try
            {
                if (json.Substring(0, 1) != "[")
                    myjson = "[" + json;
                else
                    myjson = json;
                if (json.Substring(json.Length - 1, 1) != "]")
                    myjson = myjson + "]";
            }
            catch
            {
            }
            return myjson;
        }

        public static string ConvertDataTableToXML(DataTable xmlDS)
        {
            if (null == xmlDS) return string.Empty;
            StringWriter writer = new StringWriter();
            xmlDS.WriteXml(writer);
            string xmlstr = writer.ToString();
            writer.Close();
            return xmlstr;
        }


        /// <summary>
        /// 格式货拼台台号
        /// </summary>
        /// <param name="deskName"></param>
        /// <param name="spellNumber"></param>
        /// <returns></returns>
        public static string FormatDeskSpellNumber(string deskName,string spellNumber)
        {
            if (string.IsNullOrEmpty(spellNumber)) return deskName;
            return deskName + "-" + spellNumber;
        }

        public static bool IP_Valid(string IP_Text)
        {
            //如果为空，认为验证合格
            if (string.IsNullOrEmpty(IP_Text))
            {
                return false;
            }
            //清除要验证字符串中的空格
            IP_Text = IP_Text.Trim();
            //模式字符串
            string pattern = @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$";
            //验证
            return System.Text.RegularExpressions.Regex.Match(IP_Text, pattern).Success;
        }


        #region 时间戳转时间
        public static DateTime ConvertTimestampToDateTime(string timestamp)
        {
            var tz = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1, 0, 0, 0, 0));
            return timestamp.Length == 13
                ? tz.AddMilliseconds(Convert.ToInt64(timestamp))
                : tz.AddSeconds(Convert.ToInt64(timestamp));
        }
        #endregion

        ///<summary>
        /// 通过WMI读取系统信息里的网卡MAC(方法二)
        ///</summary>
        ///<returns></returns>
        public static string GetMacByWmi(string old)
        {
            try
            {
                //创建ManagementClass对象
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();
                var macAddress = new List<string>();

                foreach (ManagementObject mo in moc)//遍历获取的集合
                {
                    if ((bool)mo["IPEnabled"])//判断IPEnabled的属性是否为true
                    {
                        if (!string.IsNullOrEmpty(old) &&
                            mo["MacAddress"].ToString().Equals(old))
                        {
                            return old;
                        }

                        macAddress.Add(mo["MacAddress"].ToString());
                    }
                }

                mc = null;
                moc = null;
                return macAddress.Count > 0 ? macAddress[0] : string.Empty;
            }
            catch { }
            return string.Empty;
        }
    }
}
